[][src]Crate runtime

Runtime is what we imagine async APIs could look like if they were part of stdlib. We want async Rust to be an experience that mirrors the quality of the standard lib. We believe that in order for Rust to succeed it's not only important to make async Rust possible, it's crucial to make async Rust feel seamless.

And the embodiment of these values is Runtime: a library crafted to empower everyone to build asynchronous software.

  • runtime agnostic: Runtime comes with minimal OS bindings out of the box, but switching to a different runtime is a matter of changing a single line.
  • await anywhere: Runtime allows you to write async main functions, async tests, and async benchmarks. Experience what first-class async support in Rust feels like.
  • built for performance: Runtime is the thinnest layer possible on top of the backing implementations. All of the speed, none of the boilerplate.

Examples

UDP Echo Server

use runtime::net::UdpSocket;

#[runtime::main]
async fn main() -> std::io::Result<()> {
    let mut socket = UdpSocket::bind("127.0.0.1:8080")?;
    let mut buf = vec![0u8; 1024];

    println!("Listening on {}", socket.local_addr()?);

    loop {
        let (recv, peer) = socket.recv_from(&mut buf).await?;
        let sent = socket.send_to(&buf[..recv], &peer).await?;
        println!("Sent {} out of {} bytes to {}", sent, recv, peer);
    }
}

To send messages do:

$ nc -u localhost 8080

More Examples

Attributes

Runtime introduces 3 attributes to enable the use of await anywhere, and swap between different runtimes. Each Runtime is bound locally to the initializing thread. This enables the testing of different runtimes during testing or benchmarking.

This example is not tested
#[runtime::main]
async fn main() {}

#[runtime::test]
async fn my_test() {}

#[runtime::bench]
async fn my_bench() {}

Runtimes

Switching runtimes is a one-line change:

This example is not tested
/// Use the default Native Runtime
#[runtime::main]
async fn main() {}

/// Use the Tokio Runtime
#[runtime::main(runtime_tokio::Tokio)]
async fn main() {}

The following backing runtimes are available:

  • Runtime Native (default) provides a thread pool, bindings to the OS, and a concurrent scheduler.
  • Runtime Tokio provides a thread pool, bindings to the OS, and a work-stealing scheduler.

Modules

net

Networking primitives for asynchronous TCP/UDP communication.

prelude

The Runtime Prelude.

task

Types and Functions for working with asynchronous tasks.

time

Types and Functions for time-related operations.

Functions

spawn

Spawn a future on the runtime's thread pool.

Attribute Macros

bench

Creates an async benchmark.

main

Defines the async main function.

test

Creates an async unit test.